import 'dart:math';
import 'dart:ui' as ui;
import 'package:aqua_plunge/http/app_manager.dart';
import 'package:aqua_plunge/record/recorder.dart';
import 'package:aqua_plunge/util/view_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/utils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'data.dart';
import 'wave.dart';
part 'recording_status_mask.dart';
part 'canvas.dart';

class SoundsMessageButton extends StatefulWidget {
  const SoundsMessageButton({
    super.key,
    this.maskData = const RecordingMaskOverlayData(),
    this.builder,
    this.onChanged,
    this.onSendSounds,
  });

  /// 自定义发送按钮视图
  final Function(
    BuildContext context,
    SoundsMessageStatus status,
  )? builder;

  /// 状态监听， 回调到外部自定义处理
  final Function(SoundsMessageStatus status)? onChanged;
  /// 发送音频 / 发送音频文字
  final Function(SendContentType type, String content)? onSendSounds;
  /// 语音输入时遮罩配置
  final RecordingMaskOverlayData maskData;

  @override
  State<SoundsMessageButton> createState() => _SoundsMessageButtonState();
}

class _SoundsMessageButtonState extends State<SoundsMessageButton> {
  /// 屏幕大小
  final scSize = Size(ScreenUtil().screenWidth, ScreenUtil().screenHeight);
  /// 遮罩图层
  OverlayEntry? _entry;
  /// 录音
  final _soundsRecorder = SoundsRecorderController();

  bool first = true;

  @override
  void initState() {
    super.initState();
    _soundsRecorder.status.addListener(() {
      widget.onChanged?.call(_soundsRecorder.status.value);
    });
  }

  @override
  void dispose() {
    _soundsRecorder.reset();
    super.dispose();
  }
  _removeMask() {
    if (_entry != null) {
      _entry!.remove();
      _entry = null;
      _soundsRecorder.updateStatus(SoundsMessageStatus.none);
    }
  }
  _showRecordingMask() {
    _entry = OverlayEntry(
      builder: (context) {
        return RepaintBoundary(
          child: RecordingStatusMaskView(
            PolymerData(_soundsRecorder, widget.maskData),
            onCancelSend: () {
              _removeMask();
            },
            onVoiceSend: () {
              widget.onSendSounds?.call(
                  SendContentType.voice, _soundsRecorder.path.value ?? '');
              _removeMask();
            },
          ),
        );
      },
    );
    Overlay.of(context).insert(_entry!);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPress: () async {

        if(!await Permission.microphone.isGranted){
          await Permission.microphone.request();
          return;
        }

        if (!await _soundsRecorder.hasPermission()) {
          if (context.mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                behavior: SnackBarBehavior.floating,
                content: Text('No recording permission obtained'),
              ),
            );
          }
          return;
        }else{
          AppManager.authorTimesPlus();
        }

        if(AppManager.getAuthorTimes() == 1){
          return;
        }
        // 是否支持录音配置
        if (!await _soundsRecorder.isEncoderSupported()) {
          return;
        }
        // 显示语音输入UI
        _showRecordingMask();
        // 录制
        _soundsRecorder.beginRec(
          onStateChanged: (state) {
            debugPrint('________  onStateChanged: $state ');
          },
          onAmplitudeChanged: (amplitude) {
            debugPrint(
                '________  onAmplitudeChanged: ${amplitude.current} , ${amplitude.max} ');
          },
          onDurationChanged: (time) {
            debugPrint('________  onDurationChanged: $time ');
          },
          onCompleted: (path, time) {
            // _removeMask();
            debugPrint('________  onCompleted: $path , $time ');

            if (time < 1) {
              _removeMask();
              showDialog(
                context: context,
                builder: (context) {
                  return CupertinoAlertDialog(
                    title: const Text('The recording time is too short'),
                    actions: [
                      CupertinoDialogAction(
                        child: const Text('Confirm'),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    ],
                  );
                },
              );
              return;
            }
            // 录制状态松开/超过时长 直接发送语音内容
            if (_soundsRecorder.status.value == SoundsMessageStatus.recording) {
              widget.onSendSounds?.call(SendContentType.voice, path!);
              _removeMask();
            }
            // 取消发送
            else if (_soundsRecorder.status.value ==
                SoundsMessageStatus.canceling) {
              _removeMask();
            }
          },
        );
      },
      onLongPressMoveUpdate: (details) {
        // 录音状态下的手势移动处理
        if (_soundsRecorder.status.value == SoundsMessageStatus.none) {
          return;
        }
        final offset = details.globalPosition;
        if ((scSize.height - offset.dy.abs()) >
            widget.maskData.sendAreaHeight) {
          _soundsRecorder.updateStatus(SoundsMessageStatus.canceling);
        } else {
          _soundsRecorder.updateStatus(SoundsMessageStatus.recording);
        }
      },
      onLongPressEnd: (details) async {
        // 手势结束音频
        _soundsRecorder.endRec();
      },
      child: ValueListenableBuilder(
        valueListenable: _soundsRecorder.status,
        builder: (context, value, child) {
          if (widget.builder != null) {
            return widget.builder?.call(context, value);
          }
          return Container(
            width: double.infinity,
            alignment: Alignment.center,
            child:Image.asset('images/icon_hold_speak.png',height: 40,),
          );
        },
      ),
    );
  }
}